<?php
declare (strict_types = 1);
namespace app\user\logic\user;

use think\db\exception\DbException;
use think\facade\Event;
use app\common\exception\LogicException;
use app\user\model\user\CreditFlow as CreditFlowModel;
use app\user\event\subscribes\user\Credit as CreditSubscribe;
use think\Model;
use think\Paginator;

/**
 * 账户积分流水接口类
 */
class CreditFlow extends CreditFlowModel
{

    /**
     * 用户积分明细
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-05-20
     *
     * @throws DbException
     */
    public function flow($append = ['alter_type', 'type_text']): Paginator
    {
        return $this->field('type,num,create_time,note,rel_type')->scope('mid')->order('create_time', 'DESC')->append($append)->paginate($this->getListRows());
    }

    /**
     * 流水记录
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-21
     *
     * @param        $uid
     * @param        $alter_type
     * @param        $num
     * @param        $credit
     * @param        $rel_type
     * @param        $rel_pk
     * @param string $note
     * @return CreditFlow|Model [type]                      [description]
     */
    public function updateFlow($uid, $alter_type, $num, $credit, $rel_type, $rel_pk, string $note = '')
    {
        $data = [
            'user_id'       => $uid,
            'type'          => $alter_type,
            'num'           => $num,
            'credit'        => $credit,
            'rel_type'      => $rel_type,
            'rel_pk'        => $rel_pk,
            'note'          => $note,
        ];

        $re = $this::create($data);
        if ( $re->isEmpty() ) throw new LogicException('流水添加失败');

        // 流水添加后处理事件
        Event::subscribe(CreditSubscribe::class);
        Event::trigger('CreditIncrease', $data);

        return $re;

    }


}
